package com.hua.yuan.live.repertory.cloud_data.loader;

import android.support.annotation.NonNull;
import com.hua.yuan.live.repertory.p2p.LiveP2pCreateRoom;
import com.hua.yuan.rtcroom.RTCRoom;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * P2P创建语聊
 *
 * @author richsjeson
 */
public class LiveP2pCreateRoomLoader {

    /**
     * 创建房间
     *
     * @param pCreateRoomId 创建房间的ID
     * @param pRctRoom      RTCRoom
     * @param pCallback     房间
     */
    public static void createRoom(@NonNull final String pCreateRoomId, @NonNull final RTCRoom pRctRoom, @NonNull final LiveP2pCreateRoom.IMessageCallBack pCallback) {

        Observable.create(new ObservableOnSubscribe<Boolean>() {

            @Override
            public void subscribe(final ObservableEmitter<Boolean> pEmitter) throws Exception {

                LiveP2pCreateRoom liveP2pCreateRoom = new LiveP2pCreateRoom();
                liveP2pCreateRoom.setCallback(pCallback);
                liveP2pCreateRoom.setCreateRoomId(pCreateRoomId);
                liveP2pCreateRoom.setRTCRomm(pRctRoom);
                liveP2pCreateRoom.start();
                pEmitter.onNext(true);
                pEmitter.onComplete();
            }

        }).subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Boolean>() {

                    private Disposable mDisposable;

                    @Override
                    public void onSubscribe(Disposable d) {
                        mDisposable = d;
                    }

                    @Override
                    public void onNext(Boolean value) {
                        mDisposable.dispose();
                    }

                    @Override
                    public void onError(Throwable e) {
                        mDisposable.dispose();
                    }

                    @Override
                    public void onComplete() {
                        mDisposable.dispose();
                    }
                });
    }

}
